package com.study.juc2;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author study
 * @version 1.0
 * @date 2020/9/20 22:04
 */
class Ticket {//资源类
    private int number = 30;

    private Lock lock = new ReentrantLock();

    public void saleTicket2() {

        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "\t卖出第:" + (number--) + "\t 还剩:" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public synchronized void saleTicket() {
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + "\t卖出第:" + (number--) + "\t 还剩:" + number);
        }
    }

}

public class SaleTicket {
    public static void main(String[] args) {

        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.saleTicket2();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.saleTicket2();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) ticket.saleTicket2();
        }, "C").start();
    }
}


